<template>
    <div :class="{'ly-is-full': isFull}">
        <div class="tableSelect" ref="tableSelect">
            <el-form :inline="true" :model="formInline" label-position="left">
                <el-form-item label="所属机构：" v-if="isSuperAdmin">
                    <el-cascader
                        v-model="formInline.organ_id"
                        :options="deptOptions"
                        :props="deptProps"
                        clearable
                        placeholder="请选择机构"
                        @change="handleDeptChange"
                        style="width: 200px"
                    ></el-cascader>
                </el-form-item>

                <el-form-item label="数据库名称：">
                    <el-input
                        v-model.trim="formInline.db_name"
                        maxlength="100"
                        clearable
                        placeholder="数据库名称"
                        @change="search"
                        style="width: 200px"
                    ></el-input>
                </el-form-item>

                <el-form-item label="数据库别名：">
                    <el-input
                        v-model.trim="formInline.db_alias"
                        maxlength="50"
                        clearable
                        placeholder="数据库别名"
                        @change="search"
                        style="width: 180px"
                    ></el-input>
                </el-form-item>

                <el-form-item label="主机地址：">
                    <el-input
                        v-model.trim="formInline.host"
                        maxlength="100"
                        clearable
                        placeholder="主机地址"
                        @change="search"
                        style="width: 180px"
                    ></el-input>
                </el-form-item>

                <el-form-item label="数据库类型：">
                    <el-select
                        v-model="formInline.db_type"
                        placeholder="请选择数据库类型"
                        clearable
                        @change="search"
                        style="width: 160px"
                    >
                        <el-option
                            v-for="item in dbTypeList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="状态：">
                    <el-select
                        v-model="formInline.is_active"
                        placeholder="请选择状态"
                        clearable
                        @change="search"
                        style="width: 130px"
                    >
                        <el-option label="启用" value="true"></el-option>
                        <el-option label="禁用" value="false"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="更新时间：">
                    <el-date-picker
                        style="width: 350px"
                        v-model="updateTimers"
                        type="datetimerange"
                        @change="updateTimeChange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    ></el-date-picker>
                </el-form-item>

                <el-form-item label="">
                    <el-button
                        @click="search"
                        type="primary"
                        icon="Search"
                        v-show="isShowBtn('dbconfig','数据库基本信息','Search')"
                    >
                        查询
                    </el-button>
                </el-form-item>

                <el-form-item label="">
                    <el-button @click="resetForm" icon="Refresh">
                        重置
                    </el-button>
                </el-form-item>

                <el-form-item label="">
                    <el-button
                        @click="handleAdd"
                        type="success"
                        icon="Plus"
                        v-show="isShowBtn('dbconfig','数据库基本信息','Create')"
                    >
                        新增
                    </el-button>
                </el-form-item>

                <el-form-item label="">
                    <el-button
                        @click="handleBatchDelete"
                        type="danger"
                        icon="Delete"
                        :disabled="!hasSelected"
                        v-show="isShowBtn('dbconfig','数据库基本信息','Delete')"
                    >
                        批量删除
                    </el-button>
                </el-form-item>
            </el-form>

            <el-table
                :height="tableHeight"
                border
                :data="tableData"
                ref="tableref"
                v-loading="loadingPage"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55"></el-table-column>

                <el-table-column type="index" width="60" align="center" label="序号">
                    <template #default="scope">
                        <span v-text="getIndex(scope.$index)"></span>
                    </template>
                </el-table-column>

                <el-table-column min-width="160" prop="db_name" label="数据库名称" show-overflow-tooltip></el-table-column>

                <el-table-column min-width="140" prop="db_alias" label="数据库别名" show-overflow-tooltip></el-table-column>

                <el-table-column min-width="120" prop="db_type" label="数据库类型">
                    <template #default="scope">
                        <el-tag :type="scope.row.db_type === 'MySQL' ? 'success' : 'primary'">
                            {{ scope.row.db_type || '未知' }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column min-width="220" label="连接信息">
                    <template #default="scope">
                        <div>主机：{{ scope.row.host }}</div>
                        <div>端口：{{ scope.row.port || '默认' }}</div>
                    </template>
                </el-table-column>

                <el-table-column min-width="140" prop="organ_name" label="所属机构" show-overflow-tooltip></el-table-column>

                <el-table-column min-width="100" label="状态">
                    <template #default="scope">
                        <el-switch
                            v-model="scope.row.is_active"
                            @change="changeStatus(scope.row)"
                            :disabled="!isShowBtn('dbconfig','数据库基本信息','Edit')"
                        ></el-switch>
                    </template>
                </el-table-column>

                <el-table-column min-width="200" label="时间信息">
                    <template #default="scope">
                        <div>创建：{{ formatDateTime(scope.row.create_datetime) }}</div>
                        <div>更新：{{ formatDateTime(scope.row.update_datetime) }}</div>
                    </template>
                </el-table-column>

                <el-table-column min-width="160" label="连接配置">
                    <template #default="scope">
                        <div>自动提交：{{ scope.row.autocommit === 1 ? '开启' : '关闭' }}</div>
                    </template>
                </el-table-column>

                <el-table-column label="操作" fixed="right" width="160">
                    <template #header>
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>操作</div>
                            <div @click="setFull">
                                <el-tooltip content="全屏" placement="bottom">
                                    <el-icon><full-screen /></el-icon>
                                </el-tooltip>
                            </div>
                        </div>
                    </template>
                    <template #default="scope">
                        <span
                            class="table-operate-btn"
                            @click="handleEdit(scope.row, 'edit')"
                            v-show="isShowBtn('dbconfig','数据库基本信息','Update')"
                        >
                            编辑
                        </span>
                        <span
                            class="table-operate-btn"
                            @click="handleEdit(scope.row, 'detail')"
                            v-show="isShowBtn('dbconfig','数据库基本信息','Retrieve')"
                        >
                            详情
                        </span>
                        <span
                            class="table-operate-btn"
                            @click="handleSingleDelete(scope.row)"
                            v-show="isShowBtn('dbconfig','数据库基本信息','Delete')"
                            style="color: #ff4d4f"
                        >
                            删除
                        </span>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 编辑弹窗 -->
            <el-dialog
                title="数据库配置编辑"
                v-model="editDialogVisible"
                width="700px"
                :close-on-click-modal="false"
                @open="handleDialogOpen"
            >
                <el-form
                    ref="editFormRef"
                    :model="editForm"
                    :rules="editRules"
                    label-width="140px"
                    size="default"
                >
                    <!-- 基础信息区域 -->
                    <el-divider content-position="left">基础信息</el-divider>

                    <el-form-item label="数据库别名" prop="db_alias">
                        <el-input
                            v-model.trim="editForm.db_alias"
                            maxlength="50"
                            placeholder="请输入数据库别名"
                            :disabled="commonDisabled"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="数据库名称" prop="db_name">
                        <el-input
                            v-model.trim="editForm.db_name"
                            maxlength="100"
                            placeholder="请输入数据库名称"
                            :disabled="commonDisabled"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="数据库描述" prop="description">
                        <el-input
                            v-model.trim="editForm.description"
                            maxlength="200"
                            placeholder="请输入数据库描述"
                            :disabled="commonDisabled"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="数据库类型" prop="db_type">
                        <el-select
                            v-model="editForm.db_type"
                            placeholder="请选择数据库类型"
                            :disabled="commonDisabled"
                        >
                            <el-option
                                v-for="item in dbTypeList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="数据库引擎" prop="engine">
                        <el-select
                            v-model="editForm.engine"
                            placeholder="请选择数据库引擎"
                            clearable
                            style="width: 100%"
                            :disabled="commonDisabled"
                        >
                            <el-option
                                v-for="(item, index) in engineOptions"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>

                    <!-- 连接信息区域 -->
                    <el-divider content-position="left">连接信息</el-divider>

                    <el-form-item label="主机地址" prop="host">
                        <el-input
                            v-model.trim="editForm.host"
                            maxlength="100"
                            placeholder="请输入主机地址"
                            :disabled="commonDisabled"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="端口" prop="port">
                        <el-input
                            v-model.number="editForm.port"
                            type="number"
                            placeholder="请输入端口号"
                            :disabled="commonDisabled"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="用户名" prop="user">
                        <el-input
                            v-model.trim="editForm.user"
                            maxlength="50"
                            placeholder="请输入数据库用户名"
                            :disabled="commonDisabled"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="密码" prop="password">
                        <el-input
                            v-model.trim="editForm.password"
                            maxlength="100"
                            type="password"
                            placeholder="请输入数据库密码（不修改请留空）"
                            :disabled="commonDisabled"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="额外选项" prop="options">
                        <el-input
                            v-model.trim="editForm.options"
                            placeholder="请输入额外连接选项"
                            :disabled="commonDisabled"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="时区" prop="time_zone">
                        <el-input
                            v-model.trim="editForm.time_zone"
                            placeholder="请输入时区（如：UTC+8）"
                            :disabled="commonDisabled"
                        ></el-input>
                    </el-form-item>

                    <!-- 连接配置区域 -->
                    <el-divider content-position="left">连接配置</el-divider>

                    <el-form-item label="自动提交">
                        <el-switch
                            v-model="editForm.autocommit"
                            active-value="1"
                            inactive-value="0"
                            :disabled="commonDisabled"
                        ></el-switch>
                    </el-form-item>

                    <el-form-item label="原子请求">
                        <el-switch
                            v-model="editForm.atomic_requests"
                            active-value="1"
                            inactive-value="0"
                            :disabled="commonDisabled"
                        ></el-switch>
                    </el-form-item>

                    <el-form-item label="连接健康检查">
                        <el-switch
                            v-model="editForm.conn_health_checks"
                            active-value="1"
                            inactive-value="0"
                            :disabled="commonDisabled"
                        ></el-switch>
                    </el-form-item>

                    <el-form-item label="最大连接时长(秒)" prop="conn_max_age">
                        <el-input
                            v-model.number="editForm.conn_max_age"
                            type="number"
                            placeholder="请输入最大连接时长"
                            :disabled="commonDisabled"
                        ></el-input>
                    </el-form-item>

                    <!-- 状态和备注区域 -->
                    <el-divider content-position="left">状态和备注</el-divider>

                    <el-form-item label="状态">
                        <el-switch
                            v-model="editForm.is_active"
                            :disabled="commonDisabled"
                        ></el-switch>
                    </el-form-item>

                    <el-form-item label="备注" prop="remark">
                        <el-input
                            v-model.trim="editForm.remark"
                            type="textarea"
                            rows="3"
                            placeholder="请输入备注信息"
                            :disabled="commonDisabled"
                        ></el-input>
                    </el-form-item>

                    <!-- 系统信息区域 -->
                    <el-divider content-position="left">系统信息</el-divider>

                    <el-form-item label="所属机构">
                        <el-cascader
                            v-model="editForm.organ_id_path"
                            :options="deptOptions"
                            :props="deptProps"
                            :disabled="systemInfoDisabled"
                            clearable
                            placeholder="请选择机构"
                            @change="handleEditDeptChange"
                            style="width: 100%"
                        ></el-cascader>
                    </el-form-item>

                    <el-form-item label="所属机构名称">
                        <el-input
                            v-model="editForm.organ_name"
                            disabled
                            placeholder="机构名称"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="所属部门ID">
                        <el-input
                            v-model="editForm.organ_id"
                            disabled
                            placeholder="部门ID"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="创建人ID">
                        <el-input
                            v-model="editForm.creator_id"
                            :disabled="systemInfoDisabled"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="最后修改人">
                        <el-input
                            v-model="editForm.modifier"
                            :disabled="systemInfoDisabled"
                        ></el-input>
                    </el-form-item>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="创建时间">
                                <el-input
                                    v-model="editForm.create_datetime"
                                    :disabled="systemInfoDisabled"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="更新时间">
                                <el-input
                                    v-model="editForm.update_datetime"
                                    :disabled="systemInfoDisabled"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <template #footer>
                    <template v-if="!isDetailMode">
                        <el-button @click="editDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitEdit">确定</el-button>
                    </template>
                </template>
            </el-dialog>

            <!-- 分页控件 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageparm.page"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageparm.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageparm.total"
                style="margin-top: 15px; text-align: right;"
            ></el-pagination>
        </div>
    </div>
</template>

<script>
import { dateFormats, isShowBtn } from "@/utils/util";
import { dbConfigInfo, apiSystemDeptTree, getEditData, submitEditData, deleteConfig, updateDatabaseStatus } from "@/api/api";
import { useMutitabsStore } from "@/store/mutitabs";
import { FullScreen } from '@element-plus/icons-vue';

export default {
    name: 'DatabaseConfig',
    components: { FullScreen },
    props: {
        isFull: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            formInline: {
                organ_id: [],
                db_name: '',
                db_alias: '',
                host: '',
                db_type: '',
                is_active: '',
                update_start_time: '',
                update_end_time: '',
                page: 1,
                limit: 10,
                organ_id_single: ''
            },
            isDetailMode: false,
            editDialogVisible: false,
            editForm: {
                id: '',
                description: '',
                modifier: '',
                dept_belong_id: '',
                update_datetime: '',
                create_datetime: '',
                db_alias: '',
                engine: '',
                db_name: '',
                host: '',
                port: null,
                user: '',
                password: '',
                options: '',
                is_active: true,
                remark: '',
                creator_id: '',
                atomic_requests: '0',
                time_zone: '',
                autocommit: '1',
                conn_health_checks: '0',
                conn_max_age: 0,
                db_type: '',
                organ_id: '',       // 从接口直接获取
                organ_name: '',     // 从接口直接获取
                organ_id_path: []   // 级联选择的完整路径（用于回显）
            },
            editRules: {
                db_alias: [
                    { required: true, message: '请输入数据库别名', trigger: 'blur' }
                ],
                db_name: [
                    { required: true, message: '请输入数据库名称', trigger: 'blur' }
                ],
                host: [
                    { required: true, message: '请输入主机地址', trigger: 'blur' }
                ],
                db_type: [
                    { required: true, message: '请选择数据库类型', trigger: 'change' }
                ],
                engine: [
                    { required: true, message: '请选择数据库引擎', trigger: 'change' }
                ],
                port: [
                    { type: 'number', min: 1, max: 65535, message: '端口必须在1-65535之间', trigger: 'blur' }
                ],
                conn_max_age: [
                    { type: 'number', min: 0, message: '最大连接时长不能为负数', trigger: 'blur' }
                ]
            },
            updateTimers: [],
            dbTypeList: [
                { label: 'MySQL', value: 'MySQL' },
                { label: 'PostgreSQL', value: 'PostgreSQL' },
                { label: 'Oracle', value: 'Oracle' },
                { label: 'SQL Server', value: 'SQL Server' },
                { label: 'MongoDB', value: 'MongoDB' }
            ],
            engineOptions: [
                { label: 'django.db.backends.mysql', value: 'django.db.backends.mysql' },
                { label: 'django.db.backends.postgresql', value: 'django.db.backends.postgresql' },
                { label: 'django.db.backends.sqlite3', value: 'django.db.backends.sqlite3' },
                { label: 'django.db.backends.oracle', value: 'django.db.backends.oracle' },
                { label: 'sql_server.pyodbc', value: 'sql_server.pyodbc' }
            ],
            deptOptions: [],
            deptProps: {
                value: 'id',
                label: 'name',
                children: 'children'
            },
            hasSelected: false,
            multipleSelection: [],
            tableData: [],
            loadingPage: false,
            pageparm: {
                page: 1,
                limit: 10,
                total: 0
            },
            tableHeight: 500
        };
    },
    methods: {
        isShowBtn,
        search() {
            this.formInline.page = 1;
            this.getData();
        },
        resetForm() {
            this.formInline = {
                organ_id: [],
                db_name: '',
                db_alias: '',
                host: '',
                db_type: '',
                is_active: '',
                update_start_time: '',
                update_end_time: '',
                page: 1,
                limit: 10,
                organ_id_single: ''
            };
            this.updateTimers = [];
            this.multipleSelection = [];
            this.hasSelected = false;
            this.getData();
        },
        updateTimeChange(val) {
            if (val && val.length === 2) {
                this.formInline.update_start_time = val[0];
                this.formInline.update_end_time = val[1];
            } else {
                this.formInline.update_start_time = '';
                this.formInline.update_end_time = '';
            }
            this.search();
        },
        handleDeptChange(val) {
            this.formInline.organ_id_single = val?.length ? val[val.length - 1] : '';
            this.search();
        },
        async getDeptTree() {
            try {
                const res = await apiSystemDeptTree();
                if (res.code === 2000) {
                    this.deptOptions = res.data.data || [];
                } else {
                    this.$message.warning('获取机构数据失败：' + (res.msg || ''));
                }
            } catch (error) {
                console.error('获取机构数据出错：', error);
                this.$message.error('获取机构数据时发生错误，请重试');
            }
        },
        handleAdd() {
            this.$emit('add');
        },
        handleBatchDelete() {
            this.$confirm(`确定要删除选中的${this.multipleSelection.length}条数据吗？`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const ids = this.multipleSelection.map(item => item.id);
                try {
                    const res = await deleteConfig({ ids: ids.join(',') });
                    if (res.code === 2000) {
                        this.$message.success('删除成功');
                        this.getData();
                        this.multipleSelection = [];
                        this.hasSelected = false;
                    } else {
                        this.$message.warning(res.msg || '删除失败');
                    }
                } catch (error) {
                    console.error('批量删除失败：', error);
                    this.$message.error('删除时发生错误');
                }
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },
        formatDateTime(time) {
            if (!time) return '暂无';
            return dateFormats(new Date(time), 'yyyy-MM-dd HH:mm:ss');
        },
        async handleEdit(row, type) {
            // 重置表单
            if (this.$refs.editFormRef) {
                this.$refs.editFormRef.resetFields();
            }
            this.editDialogVisible = true;
            this.loadingPage = true;
            this.isDetailMode = type === 'detail';

            // 确保机构树形数据已加载（用于级联路径回显）
            if (this.deptOptions.length === 0) {
                await this.getDeptTree();
            }

            try {
                const res = await getEditData({ id: row.id });
                if (res.code === 2000) {
                    const actualData = res.data.data;
                    // 直接使用接口返回的organ_id和organ_name
                    this.editForm = {
                        ...actualData,
                        is_active: actualData.is_active === true || actualData.is_active === 1 || actualData.is_active === 'true',
                        autocommit: actualData.autocommit ? '1' : '0',
                        atomic_requests: actualData.atomic_requests ? '1' : '0',
                        conn_health_checks: actualData.conn_health_checks ? '1' : '0',
                        organ_id: actualData.organ_id,       // 直接赋值
                        organ_name: actualData.organ_name,   // 直接赋值
                        organ_id_path: []                   // 等待弹窗打开时回显路径
                    };
                } else {
                    this.$message.warning(res.msg || '获取数据失败');
                    this.editDialogVisible = false;
                }
            } catch (error) {
                console.error('获取编辑数据失败：', error);
                this.$message.error('获取数据时发生错误');
                this.editDialogVisible = false;
            } finally {
                this.loadingPage = false;
            }
        },
        async submitEdit() {
            this.$refs.editFormRef.validate(async (valid) => {
                if (valid) {
                    this.loadingPage = true;
                    const submitData = {
                        ...this.editForm,
                        autocommit: this.editForm.autocommit === '1' ? 1 : 0,
                        atomic_requests: this.editForm.atomic_requests === '1' ? 1 : 0,
                        conn_health_checks: this.editForm.conn_health_checks === '1' ? 1 : 0,
                        password: this.editForm.password || undefined
                    };
                    try {
                        const res = await submitEditData(submitData);
                        if (res.code === 2000) {
                            this.$message.success('编辑成功');
                            this.editDialogVisible = false;
                            this.getData();
                        } else {
                            this.$message.warning(res.msg || '编辑失败');
                        }
                    } catch (error) {
                        console.error('提交编辑失败：', error);
                        this.$message.error('提交时发生错误');
                    } finally {
                        this.loadingPage = false;
                    }
                }
            });
        },
        handleSingleDelete(row) {
            this.$confirm(`确定要删除【${row.db_alias}】吗？`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const res = await deleteConfig({ id: row.id });
                    if (res.code === 2000) {
                        this.$message.success('删除成功');
                        this.getData();
                    } else {
                        this.$message.warning(res.msg || '删除失败');
                    }
                } catch (error) {
                    console.error('删除失败：', error);
                    this.$message.error('删除时发生错误');
                }
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },
        changeStatus(row) {
            const newStatus = !row.is_active;
            this.$confirm(`确定要${newStatus ? '启用' : '禁用'}【${row.db_alias}】吗？`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const res = await updateDatabaseStatus({ id: row.id, is_active: newStatus });
                    if (res.code === 2000) {
                        this.$message.success('状态更新成功');
                        this.getData();
                    } else {
                        row.is_active = !newStatus;
                        this.$message.warning(res.msg || '状态更新失败');
                    }
                } catch (error) {
                    row.is_active = !newStatus;
                    console.error('状态更新失败：', error);
                    this.$message.error('状态更新时发生错误');
                }
            }).catch(() => {
                row.is_active = !newStatus;
            });
        },
        async getData() {
            this.loadingPage = true;
            const queryParams = {
                ...this.formInline,
                organ_id: this.formInline.organ_id_single
            };
            delete queryParams.organ_id_single;
            try {
                const res = await dbConfigInfo(queryParams);
                if (res.code === 2000) {
                    this.tableData = res.data.data || [];
                    this.pageparm = {
                        page: res.data.page || 1,
                        limit: res.data.limit || 10,
                        total: res.data.total || 0
                    };
                } else {
                    this.$message.warning(res.msg || '获取数据失败');
                    this.tableData = [];
                    this.pageparm.total = 0;
                }
            } catch (error) {
                console.error('获取列表数据失败：', error);
                this.$message.error('获取数据时发生错误');
                this.tableData = [];
                this.pageparm.total = 0;
            } finally {
                this.loadingPage = false;
            }
        },
        getIndex($index) {
            return (this.pageparm.page - 1) * this.pageparm.limit + $index + 1;
        },
        handleSizeChange(limit) {
            this.formInline.limit = limit;
            this.getData();
        },
        handleCurrentChange(page) {
            this.formInline.page = page;
            this.getData();
        },
        handleSelectionChange(selection) {
            this.multipleSelection = selection;
            this.hasSelected = selection.length > 0;
        },
        setFull() {
            this.isFull = !this.isFull;
            window.dispatchEvent(new Event('resize'));
            this.$nextTick(() => {
                this.tableHeight = window.innerHeight - 200;
            });
        },
        // 机构选择变化时，同步更新organ_id和organ_name
        handleEditDeptChange(val) {
            if (!val || val.length === 0) {
                this.editForm.organ_id = '';
                this.editForm.organ_name = '';
                return;
            }
            // 更新机构ID（级联最后一项）
            this.editForm.organ_id = val[val.length - 1];
            // 从deptOptions中查询机构名称（手动选择时使用）
            const findDeptName = (options, targetId) => {
                for (const option of options) {
                    if (option.id === targetId) return option.name;
                    if (option.children && option.children.length > 0) {
                        const name = findDeptName(option.children, targetId);
                        if (name) return name;
                    }
                }
                return '未知机构';
            };
            this.editForm.organ_name = findDeptName(this.deptOptions, this.editForm.organ_id);
        },
        // 弹窗打开时，回显级联选择框路径
        handleDialogOpen() {
            if (this.editForm.organ_id) {
                // 根据organ_id获取级联完整路径
                const findDeptPath = (options, targetId, path = []) => {
                    for (const option of options) {
                        const newPath = [...path, option.id];
                        if (option.id === targetId) return newPath;
                        if (option.children && option.children.length > 0) {
                            const result = findDeptPath(option.children, targetId, newPath);
                            if (result) return result;
                        }
                    }
                    return null;
                };
                this.editForm.organ_id_path = findDeptPath(this.deptOptions, this.editForm.organ_id) || [];
            }
        }
    },
    computed: {
        isSuperAdmin() {
            const mutitabsStore = useMutitabsStore();
            return mutitabsStore.userName === '超级管理员';
        },
        systemInfoDisabled() {
            return this.isDetailMode || !this.isSuperAdmin;
        },
        commonDisabled() {
            return this.isDetailMode;
        }
    },
    watch: {
        hasSelected(newVal) {
            this.$emit('selectedChange', newVal);
        }
    },
    created() {
        this.getDeptTree().then(() => {
            this.getData();
        });
    },
    mounted() {
        this.tableHeight = window.innerHeight - 200;
        window.addEventListener('resize', () => {
            this.tableHeight = window.innerHeight - 200;
        });
    },
    unmounted() {
        window.removeEventListener('resize', () => {
            this.tableHeight = window.innerHeight - 200;
        });
    }
};
</script>

<style scoped>
.tableSelect {
    margin-bottom: 16px;
    padding: 10px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

::v-deep .el-form-item {
    margin-right: 10px;
    margin-bottom: 15px;
}

.table-operate-btn {
    margin-right: 10px;
    color: #409EFF;
    cursor: pointer;
}

::v-deep .el-dialog__body {
    max-height: 60vh;
    overflow-y: auto;
    padding: 20px;
}
</style>